package com.oyjd.framework.util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.Cipher;

/**
 * 简单加解密
 * 
 * @author 欧建东
 * @email oyjd@163.com
 * 
 */
public class SecurityUtil {
	/**
	 * MD5单向加密
	 * 
	 * @param obj
	 * @return
	 */
	public static byte[] encryptMD5(byte[] obj) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(obj);
			return md.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * SHA单向加密
	 * 
	 * @param obj
	 * @return
	 */
	public static byte[] encryptSHA(byte[] obj) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA");
			md.update(obj);
			return md.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		try {

			String encryptText = "encryptText";
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
			keyPairGen.initialize(512);
			KeyPair keyPair = keyPairGen.generateKeyPair();
			// Generate keys
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
			byte[] e = keyPairEncrypt(publicKey, encryptText.getBytes());
			byte[] de = keyPairDecrypt(privateKey, e);
			System.out.println(bytesToString(e));
			System.out.println(bytesToString(de));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Change byte array to String.
	 * 
	 * @return byte[]
	 */
	public static String bytesToString(byte[] encrytpByte) {
		String result = "";
		for (Byte bytes : encrytpByte) {
			result += (char) bytes.intValue();
		}
		return result;
	}

	/**
	 * Encrypt String.
	 * 
	 * @return byte[]
	 */
	public static byte[] keyPairEncrypt(RSAPublicKey publicKey, byte[] obj) {
		if (publicKey != null) {
			try {
				Cipher cipher = Cipher.getInstance("RSA");
				cipher.init(Cipher.ENCRYPT_MODE, publicKey);
				return cipher.doFinal(obj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * Basic decrypt method
	 * 
	 * @return byte[]
	 */
	public static byte[] keyPairDecrypt(RSAPrivateKey privateKey, byte[] obj) {
		if (privateKey != null) {
			try {
				Cipher cipher = Cipher.getInstance("RSA");
				cipher.init(Cipher.DECRYPT_MODE, privateKey);
				return cipher.doFinal(obj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
